<template>
  <Page class="bg-[#000] min-h-screen">
    <PageHeader title="视频播放" :show-back="true" />
    
    <!-- 视频播放器区域 -->
    <view class="w-full bg-[#000] h-[400rpx] relative">
      <!-- 视频播放器 -->
      <video
        v-if="currentVideo"
        :src="getFullPath(currentVideo.videoUrl)"
        :poster="getFullPath(currentVideo.coverUrl)"
        class="w-full h-[400rpx] object-cover"
        controls
        autoplay
        :title="currentVideo.title"
        @error="onVideoError"
        @load="onVideoLoad"
      />
      
      <!-- 视频加载中 -->
      <view v-else class="w-full h-[400rpx] bg-[#1a1a1a] flex items-center justify-center">
        <view class="text-white text-[28rpx]">加载中...</view>
      </view>
    </view>

    <!-- 视频信息区域 -->
    <view class="bg-white p-[32rpx] mb-[16rpx]">
      <view class="text-[32rpx] font-bold mb-[16rpx] text-[#222]">{{ currentVideo?.title || '加载中...' }}</view>
      <view class="flex items-center text-[24rpx] text-[#666] mb-[16rpx]">
        <view class="flex items-center mr-[24rpx]">
          <IconFont name="clock" class="text-[20rpx] mr-[8rpx]" />
          <span>时长: {{ currentVideo?.duration || '--' }}</span>
        </view>
        <view class="flex items-center">
          <IconFont name="date" class="text-[20rpx] mr-[8rpx]" />
          <span>上课时间: {{ formatDateTime(currentVideo?.date_time) }}</span>
        </view>
      </view>
      <view class="flex items-center text-[26rpx] text-[#333] leading-[1.6]">
        <!-- <IconFont name="video" class="text-[24rpx] mr-[8rpx] text-[#165DFF]" /> -->
        <span>{{ courseDetail?.title || '课程信息加载中...' }}</span>
      </view>
    </view>

    <!-- 章节列表 -->
    <view class="bg-white">
      <view class="px-[32rpx] py-[24rpx] text-[30rpx] font-bold border-b border-[#eee] bg-[#f9f9f9] flex items-center">
        <IconFont name="horizontal" class="text-[28rpx] mr-[12rpx] text-[#165DFF]" />
        
        <span>课程目录</span>
      </view>
      <view 
        v-for="(chapter, index) in lessons" 
        :key="chapter.id" 
         @click="switchVideo(chapter)"
        class="px-[32rpx] py-[24rpx] border-b border-[#eee] flex items-center transition-all duration-200"
        :class="{ 
          'bg-[#f0f8ff] border-l-[4rpx] border-l-[#165DFF] shadow-sm': currentVideo?.id === chapter.id,
          'hover:bg-[#f5f5f5]': currentVideo?.id !== chapter.id
        }"
      >
        <view class="flex-1">
          <view class="flex items-center mb-[8rpx]">
            <view 
              class="w-[8rpx] h-[8rpx] rounded-full mr-[12rpx] transition-all duration-200"
              :class="{ 
                'bg-[#165DFF]': currentVideo?.id === chapter.id,
                'bg-[#ddd]': currentVideo?.id !== chapter.id
              }"
            ></view>
            <view 
              class="text-[28rpx] transition-colors duration-200"
              :class="{ 
                'text-[#165DFF] font-semibold': currentVideo?.id === chapter.id,
                'text-[#333]': currentVideo?.id !== chapter.id
              }"
            >
              {{ chapter.title }}
            </view>
          </view>
          <view class="flex items-center text-[24rpx] text-[#666] ml-[20rpx]">
            <IconFont name="clock" class="text-[18rpx] mr-[6rpx]" />
            <span>时长: {{ chapter.duration }}</span>
          </view>
        </view>
        <view class="flex items-center">
          <view 
            v-if="currentVideo?.id === chapter.id" 
            class="text-[#165DFF] text-[24rpx] mr-[16rpx] font-medium flex items-center"
          >
            <IconFont name="play-start" class="text-[20rpx] mr-[4rpx]" />
            <span>正在播放</span>
          </view>
          <!-- <view 
            v-if="chapter.videoUrl"
            class="w-[60rpx] h-[60rpx] rounded-full flex items-center justify-center transition-all duration-200 cursor-pointer shadow-md"
            :class="{ 
              'bg-[#FF4D4F] text-white shadow-[#FF4D4F]/30': currentVideo?.id === chapter.id,
              'bg-[#165DFF] text-white hover:bg-[#0d4bb8] hover:shadow-lg': currentVideo?.id !== chapter.id
            }"
            @click="switchVideo(chapter)"
          >
            <IconFont 
              :name="currentVideo?.id === chapter.id ? 'pause' : 'play'" 
              class="text-[28rpx]"
            />
          </view>
          <view 
            v-else
            class="w-[60rpx] h-[60rpx] rounded-full bg-[#f5f5f5] flex items-center justify-center shadow-sm"
          >
            <IconFont name="lock" class="text-[28rpx] text-[#999]" />
          </view> -->
        </view>
      </view>
      
      <!-- 空状态 -->
      <view v-if="lessons.length === 0" class="px-[32rpx] py-[60rpx] text-center">
        <IconFont name="video" class="text-[80rpx] text-[#ddd] mb-[16rpx]" />
        <view class="text-[26rpx] text-[#999]">暂无章节内容</view>
      </view>
    </view>
  </Page>
</template>

<script setup lang="ts">
import Taro from "@tarojs/taro";
import { ref, onMounted } from "vue";
import PageHeader from "@/components/PageHeader.vue";
import { getCurrentInstance } from "@tarojs/runtime";
import { getFullPath, post } from "@/utils/request";
import { IconFont } from '@nutui/icons-vue-taro';

/**
 * 视频播放页面
 * @description 视频播放器、章节列表、自动切换播放对应内容
 */

// 课程详情数据
const courseDetail = ref<any>({
  id: null,
  title: null,
  cover: null,
  price: null,
  teacher_name: null,
  teachers_introduction: null,
  member_number: null,
  cycle: null,
  byStatus: null,
  online: null,
});

// 章节列表数据
const lessons = ref<any[]>([]);

// 当前播放的视频
const currentVideo = ref<any>(null);

// 当前章节ID（从URL参数获取）
const currentChapterId = ref<number | null>(null);

// 主课程ID（从URL参数获取）
const courseId = ref<number | null>(null);

// 获取当前实例和路由参数
const instance = getCurrentInstance();

/**
 * 页面初始化
 */
onMounted(() => {
  // 从URL参数获取主课程ID和章节ID
  const courseIdParam = instance.router?.params.id as string;
  const chapterIdParam = instance.router?.params.chapter as string;
  
  if (courseIdParam && !isNaN(parseInt(courseIdParam))) {
    courseId.value = parseInt(courseIdParam);
    console.log('主课程ID:', courseId.value);
  }
  
  if (chapterIdParam && !isNaN(parseInt(chapterIdParam))) {
    currentChapterId.value = parseInt(chapterIdParam);
    console.log('当前章节ID:', currentChapterId.value);
  }
  
  // 初始化页面数据
  initPageData();
});

/**
 * 初始化页面数据
 */
const initPageData = async () => {
  try {
    // 1. 获取课程详情
    await getCourseDetail();
    
    // 2. 获取章节列表
    await getChapterList();
    
    // 3. 自动切换到指定章节
    if (currentChapterId.value) {
      autoSwitchToChapter();
    }
  } catch (error) {
    console.error('页面初始化失败:', error);
    Taro.showToast({ title: '页面加载失败', icon: 'none' });
  }
};

/**
 * 获取课程详情
 */
const getCourseDetail = async () => {
  try {
    // 直接使用主课程ID获取课程详情
    if (!courseId.value) {
      throw new Error('主课程ID不能为空');
    }
    
    const courseRes = await post('/training/getById', { trainingId: courseId.value });
    if (courseRes.code === 0) {
      courseDetail.value = {
        id: courseRes.data.columns.id,
        title: courseRes.data.columns.title,
        cover: courseRes.data.columns.cover,
        price: courseRes.data.columns.price,
        teacher_name: courseRes.data.columns.teacher_name,
        teachers_introduction: courseRes.data.columns.teachers_introduction,
        member_number: courseRes.data.columns.member_number,
        cycle: courseRes.data.columns.cycle,
        byStatus: courseRes.data.columns.byStatus,
        online: courseRes.data.columns.online,
      };
      console.log('课程详情:', courseDetail.value);
    }
  } catch (error) {
    console.error('获取课程详情失败:', error);
    throw error;
  }
};

/**
 * 获取章节列表
 */
const getChapterList = async () => {
  try {
    // 直接使用主课程ID获取章节列表
    if (!courseId.value) {
      throw new Error('主课程ID不能为空');
    }
    
    const lessonsRes = await post('/training/list', { trainingId: courseId.value });
    if (lessonsRes.code === 0) {
      lessons.value = lessonsRes.data.map((item: any) => ({
        id: item.columns.id,
        title: item.columns.title,
        videoUrl: item.columns.videoUrl,
        coverUrl: item.columns.coverUrl,
        duration: item.columns.duration,
        date_time: item.columns.date_time,
        trainingId: item.columns.trainingId,
      }));
      console.log('章节列表:', lessons.value);
    }
  } catch (error) {
    console.error('获取章节列表失败:', error);
    throw error;
  }
};

/**
 * 自动切换到指定章节
 */
const autoSwitchToChapter = () => {
  if (!currentChapterId.value || lessons.value.length === 0) {
    return;
  }
  
  // 查找指定章节
  const targetChapter = lessons.value.find(chapter => chapter.id === currentChapterId.value);
  if (targetChapter) {
    currentVideo.value = targetChapter;
    console.log('自动切换到章节:', targetChapter.title);
  } else {
    // 如果找不到指定章节，默认播放第一个有视频的章节
    const firstVideoChapter = lessons.value.find(chapter => chapter.videoUrl);
    if (firstVideoChapter) {
      currentVideo.value = firstVideoChapter;
      console.log('默认播放第一个章节:', firstVideoChapter.title);
    }
  }
};

/**
 * 切换视频
 */
const switchVideo = (chapter: any) => {
  // if (!chapter.videoUrl) {
  //   Taro.showToast({ title: '该章节暂无视频', icon: 'none' });
  //   return;
  // }
  
  currentVideo.value = chapter;
  console.log('切换到章节:', chapter.title);
  
  // 更新URL参数（可选）
  // Taro.redirectTo({
  //   url: `/pages/course/video-player?id=${courseId.value}&chapter=${chapter.id}`,
  // });
};

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '--';
  
  try {
    const date = new Date(dateTime);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    return dateTime;
  }
};

/**
 * 视频加载事件
 */
const onVideoLoad = () => {
  console.log('视频加载完成');
};

/**
 * 视频错误事件
 */
const onVideoError = (error: any) => {
  console.error('视频播放错误:', error);
  Taro.showToast({ title: '视频播放失败', icon: 'none' });
};

/**
 * 返回课程详情页
 */
const goBack = () => {
  if (courseDetail.value.id) {
    Taro.redirectTo({
      url: `/pages/course/detail?id=${courseDetail.value.id}`,
    });
  } else {
    Taro.navigateBack();
  }
};
</script>

<style scoped lang="scss">
/* 视频播放器样式 */
video {
  width: 100%;
  height: 400rpx;
  object-fit: cover;
}

/* 章节列表样式 */
.chapter-item {
  transition: all 0.3s ease;
}

.chapter-item:hover {
  background-color: #f5f5f5;
}

.chapter-item.active {
  background-color: #f0f8ff;
  border-left: 4rpx solid #165DFF;
}

/* 当前播放章节高亮效果 */
.chapter-playing {
  background: linear-gradient(90deg, #f0f8ff 0%, #e6f3ff 100%);
  border-left: 4rpx solid #165DFF;
  box-shadow: 0 2rpx 8rpx rgba(22, 93, 255, 0.1);
}

/* 播放按钮样式 */
.play-button {
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.play-button:hover {
  transform: scale(1.05);
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.2);
}

.play-button.playing {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.3);
  }
  50% {
    box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.6);
  }
  100% {
    box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.3);
  }
}

/* 章节状态指示器 */
.status-indicator {
  transition: all 0.3s ease;
}

.status-indicator.active {
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-4rpx);
  }
  60% {
    transform: translateY(-2rpx);
  }
}

/* 文本截断 */
.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 响应式适配 */
@media (max-width: 750rpx) {
  .chapter-title {
    font-size: 26rpx;
  }
  
  .chapter-duration {
    font-size: 22rpx;
  }
}

/* 图标样式优化 */
.icon-font {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 阴影效果 */
.shadow-custom {
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.shadow-custom:hover {
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
}
</style>
